<?php
namespace app\common\controller;

use think\Controller;

class Base extends Controller
{

    protected $get;
    protected $post;
    protected $param;

    public function initialize()
    {
        parent::initialize();
        $this->get = input('get.', null, 'trim');
        $this->post = input('post.', null, 'trim');
        $this->param = input('param.', null, 'trim');
        //解决线上不过滤空格问题
        array_walk_recursive($this->get, [$this,'filterParams']);
        array_walk_recursive($this->post, [$this,'filterParams']);
        array_walk_recursive($this->param, [$this,'filterParams']);
        $this->_header();
    }

    protected function filterParams(&$val, $key){
        $val = trim($val);
    }

    protected function ajaxReturn($data = array(), $msg= ''){
        $res['status'] = $data === false ? false : true;
        $res['data'] = $data;
        $res['msg'] = $msg ? $msg : ($data === false ? '操作失败' : '操作成功');
        exit(json_encode($res, JSON_UNESCAPED_UNICODE));
    }

    /**
     * 检查必填参数
     * @param array|string
     * @return bool
     */
    protected function checkParams($param){
        if (empty($param)) return false;
        if (is_string($param)) $param = explode(',', $param);
        foreach ($param as $val){
            if (strpos($val, '||') !== false){
                $tmp_val = explode('||', $val);
                if (!isset($this->param[trim($tmp_val[0])]) && !isset($this->param[trim($tmp_val[1])])){
                    $this->ajaxReturn(false, 'param ' . $tmp_val[0] . ' or ' . $tmp_val[1] . ' error');
                }
            }else if(!isset($this->param[trim($val)]) || $this->param[trim($val)] === '') {
                $this->ajaxReturn(false, 'param ' . $val . ' error');
            }
        }
        foreach ($this->post as $key => $val){
            if (is_null($val) || $val == 'null') unset($this->post[$key]);
        }

        return $this;
    }

    private function _header(){
        
        $allow_origin = ["http://192.168.0.32:8080", "http://localair.com", "http://192.168.0.32:8081", "http://192.168.0.32:8082", "http://192.168.0.32:8083", "http://192.168.0.32:8084", "http://192.168.0.32:8085"];
        
        $origin = isset($_SERVER['HTTP_ORIGIN']) ? $_SERVER['HTTP_ORIGIN'] : '';
        header("Content-type: text/html; charset=utf-8");
        header("Access-Control-Allow-Credentials:true");
        if (in_array($origin, $allow_origin)) {
            header('Access-Control-Allow-Origin:' . $origin);
        }
    }
}


